package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.Service.BookService;
import com.example.demo.commom.Result;
import com.example.demo.entity.Book;
import com.example.demo.mapper.BookMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/book")
@Slf4j
public class BookController {
    @Resource
    BookMapper BookMapper;
    @Autowired
    BookService bookService;

    @PostMapping
    public Result<?> save(@RequestBody Book Book){
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("isbn",Book.getIsbn());
        List<Book> existBooks = BookMapper.selectList(queryWrapper);
        if (existBooks.isEmpty()){
            BookMapper.insert(Book);
            return Result.success();
        }else{
            if(existBooks.get(0).getName().equals(Book.getName())){
                BookMapper.insert(Book);
                return Result.success();
            }else {
                return Result.error("403","条形码编号已存在");
            }
        }
    }
    @PutMapping("/update")
    public  Result<?> update(@RequestBody Book Book){
        log.info("update Book: " + Book);
        BookMapper.updateById(Book);
        return Result.success();
    }

    //    批量删除
    @PostMapping("/deleteBatch")
    public  Result<?> deleteBatch(@RequestBody List<Integer> ids){
        BookMapper.deleteBatchIds(ids);
        return Result.success();
    }
    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id){
        BookMapper.deleteById(id);
        return Result.success();
    }

    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search1,
                              @RequestParam(defaultValue = "") String search2,
                              @RequestParam(defaultValue = "") String search3){

        LambdaQueryWrapper<Book> wrappers = Wrappers.<Book>lambdaQuery();

        // 应用搜索条件
        if(StringUtils.isNotBlank(search1)){
            wrappers.eq(Book::getBookIsbn, search1);
        }
        if(StringUtils.isNotBlank(search2)){
            wrappers.like(Book::getName, search2);
        }
        if(StringUtils.isNotBlank(search3)){
            wrappers.like(Book::getAuthor, search3);
        }

        // 执行查询，获取所有符合条件的图书
        List<Book> bookList = BookMapper.selectList(wrappers);

        // 使用Map去重，确保每个bookIsbn只保留一个图书
        Map<String, Book> uniqueBooks = new HashMap<>();
        for (Book book : bookList) {
            // 保留第一个出现的图书（如果有需要可以调整保留规则）
            uniqueBooks.putIfAbsent(book.getBookIsbn(), book);
        }

        // 从Map中获取去重后的图书列表
        List<Book> uniqueBookList = new ArrayList<>(uniqueBooks.values());

        // 处理分页逻辑
        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, uniqueBookList.size());
        List<Book> paginatedBooks = uniqueBookList.subList(startIndex, endIndex);

        // 创建分页结果
        Page<Book> BookPage = new Page<>(pageNum, pageSize, uniqueBookList.size());
        BookPage.setRecords(paginatedBooks);

        return Result.success(BookPage);
    }


    //回调图书照片
    @PostMapping("/photo")
    public Result<?> updatePhoto
    (@RequestParam String bookIsbn, @RequestParam String url) {
        Book book = new Book();
        book.setIsbn(bookIsbn);
        book.setPhoto(url);  // 只设置 photo 字段
        boolean success = bookService.updateById(book);
        return success ? Result.success() : Result.error("405","更新封面失败");
    }

    //借阅排行榜
    @GetMapping("/borrow-rank")
    public  Result<?> getBorrowRank() {
        return Result.success(BookMapper.getBorrowRank());
    }

    @GetMapping("/copies")
    public Result<?> getBooksByBookIsbn(@RequestParam String bookIsbn) {
        log.info("图书编号: " + bookIsbn);
        List<Book> books = bookService.getBooksByBookIsbn(bookIsbn);
        if (books.isEmpty()) {
            return Result.error("404", "没有找到副本信息");
        } else {
            return Result.success(books);
        }
    }


}

